package com.ddc.study.base;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import androidx.annotation.NonNull;

/**
 * Created on 2018/8/25.
 *
 * @author lshun
 * @version 1.0
 */
class CrashHandler implements Thread.UncaughtExceptionHandler {
    private static final String TAG = "CrashHandler";

    private Context mContext;

    CrashHandler(Context context) {
        Thread.setDefaultUncaughtExceptionHandler(this);
        mContext = context.getApplicationContext();
    }

    @Override
    public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
        handlerException(t, e);

        // 退出程序
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(1);
    }

    private void handlerException(@NonNull Thread t, @NonNull Throwable e) {
        // 收集设备参数信息
        collectDeviceInfo(mContext);
        // 保存日志文件
        saveCrashInfo2File(t, e);
    }

    /**
     * 收集设备参数信息
     */
    private void collectDeviceInfo(Context context) {
        try {
            PackageInfo pi = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "package not found", e);
        }
    }

    /**
     * 保存错误信息到文件中
     */
    private void saveCrashInfo2File(@NonNull Thread t, @NonNull Throwable e) {
    }
}
